import { ActivatedRouteSnapshot, RouterStateSnapshot, Params } from '@angular/router';
import { RouterStateSerializer } from '@ngrx/router-store';
import { Breadcrumb } from '../../shared';

export interface RouterStateUrl {
    url: string;
    queryParams: Params;
    params: Params;
    breadcrumb: Breadcrumb[];
}

export class CustomSerializer implements RouterStateSerializer<RouterStateUrl> {

    serialize(routerState: RouterStateSnapshot): RouterStateUrl {
        const { url } = routerState;
        const { queryParams } = routerState.root;
        const breadcrumb: Breadcrumb[] = this.breadcrumbBuilder(routerState.root);

        let state: ActivatedRouteSnapshot = routerState.root;
        while(state.firstChild) {
            state = state.firstChild;
        }
        const { params } = state

        return {
            url,
            queryParams,
            params,
            breadcrumb
        }
    }

    private breadcrumbBuilder(
        state: ActivatedRouteSnapshot, 
        initial: Breadcrumb[] = [{ name: '首页', url: '/' }]
    ): Breadcrumb[] {
        let breadcrumb: Breadcrumb[] = initial;
        const lastBreadcrumb: Breadcrumb = breadcrumb[breadcrumb.length - 1];
        const lastUrl: string = lastBreadcrumb.url === '/' ? '' : lastBreadcrumb.url;
        if(state.routeConfig && state.routeConfig.path) {
            breadcrumb.push({
                name: state.data.name,
                url: `${lastUrl}/${state.routeConfig.path}`
            });
        }
        if(state.firstChild) {
            breadcrumb = this.breadcrumbBuilder(state.firstChild, breadcrumb);
        }
        return breadcrumb;
    }

    
}